package com.gitee.fsmxm.thinking.in.spring.bean.definition;

import com.gitee.fsmxm.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Import;

/**
 * 注解方式bean定义 demo
 */
@Import(Config.class) // 导入配置方式
public class AnnotationBeanDefinitionDemo {

    public static void main(String[] args) {

        // 注解配置应用上下文
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 注册配置类
        applicationContext.register(AnnotationBeanDefinitionDemo.class);

        // register api 注册
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;

        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id", 1L).addPropertyValue("name", "小马哥");
        // 命名方式注册
        registry.registerBeanDefinition("xmg", beanDefinitionBuilder.getBeanDefinition());
        // 非命名方式注册
        BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(), registry);

        // 启动应用上下文
        applicationContext.refresh();

        // 依赖查找
        System.out.println(applicationContext.getBeansOfType(User.class));
        System.out.println(applicationContext.getBeansOfType(Config.class));

        // 关闭容器
        applicationContext.close();

    }

}
